package leetcode.datastructure.graph;

/**
 * 岛的思想：所有关联数据蔓延消除
 */
public class Program200Office {

    // 遍历上、左 结果便利不全，进一步 上右、下左、下右
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }

        int row = grid.length;
        int col = grid[0].length;
        int res = 0;
        for (int i = 0; i < row; ++i) {
            for (int j = 0; j < col; ++j) {
                if (grid[i][j] == '1') {
                    ++res;
                    dfs(grid, i, j);
                }
            }
        }

        return res;
    }

    /**
     * 所有关联数据蔓延消除
     * @param grid
     * @param i
     * @param j
     */
    public void dfs(char[][] grid, int i, int j) {
        int row = grid.length;
        int col = grid[0].length;

        if (i < 0 || j < 0 || i >= row || j >= col || grid[i][j] == '0') {
            return;
        }

        grid[i][j] = '0';
        dfs(grid, i - 1, j);
        dfs(grid, i + 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
    }

    public static void main(String[] args) {
        Program200Office myStack = new Program200Office();
//        char[][] board = {
//                {'1','1','1','1','0'}
//                ,{'1','1','0','1','0'}
//                ,{'1','1','0','0','0'}
//                ,{'0','0','0','0','0'}
//        };
//        System.out.println(myStack.numIslands(board)); // 返回
//        char[][] board2 = {
//                {'1','1','0','0','0'}
//                ,{'1','1','0','0','0'}
//                ,{'0','0','1','0','0'}
//                ,{'0','0','0','1','1'}
//        };
//        System.out.println(myStack.numIslands(board2)); // 返回
        char[][] board3 = {
                {'1','1','1'}
                ,{'0','1','0'}
                ,{'1','1','1'}
        };
        System.out.println(myStack.numIslands(board3)); // 返回
    }
}
